package com.minimalist.common.utils;

import java.security.SecureRandom;
import java.util.UUID;

/**
 * 生成工具类
 *
 * @author 11987
 */
public class GenerateUtil{

    /**
     * 私有构造函数，防止实例化
     */
    private GenerateUtil(){
        throw new IllegalStateException("工具类不允许实例化");
    }

    /**
     * 生成指定长度的随机密码，包含数字、大小写字母和特殊符号
     *
     * @param length 密码长度
     * @return 随机密码
     */
    public static String generateRandomPassword(int length){
        // 定义字符集
        String upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lowerChars = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String specialChars = "!@#$%&*.?";
        String allChars = upperChars + lowerChars + numbers + specialChars;
        SecureRandom random = new SecureRandom();
        StringBuilder password = new StringBuilder(length);
        // 确保密码至少包含一个大写字母、一个小写字母、一个数字和一个特殊字符
        password.append(upperChars.charAt(random.nextInt(upperChars.length())));
        password.append(lowerChars.charAt(random.nextInt(lowerChars.length())));
        password.append(numbers.charAt(random.nextInt(numbers.length())));
        password.append(specialChars.charAt(random.nextInt(specialChars.length())));
        // 生成剩余的随机字符
        for (int i = 4; i < length; i++){
            password.append(allChars.charAt(random.nextInt(allChars.length())));
        }
        // 打乱密码字符顺序
        char[] passwordArray = password.toString().toCharArray();
        for (int i = 0; i < passwordArray.length; i++){
            int j = random.nextInt(passwordArray.length);
            char temp = passwordArray[i];
            passwordArray[i] = passwordArray[j];
            passwordArray[j] = temp;
        }
        return new String(passwordArray);
    }

    /**
     * 生成UUID（无连字符）
     *
     * @return UUID字符串（无连字符）
     */
    public static String generateUuid(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 生成指定长度的随机数字
     *
     * @param length 长度
     * @return 随机数字字符串
     */
    public static String generateRandomNumbers(int length){
        String numbers = "0123456789";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++){
            sb.append(numbers.charAt(random.nextInt(numbers.length())));
        }
        return sb.toString();
    }

    /**
     * 生成指定长度的随机字母
     *
     * @param length 长度
     * @return 随机字母字符串
     */
    public static String generateRandomLetters(int length){
        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++){
            sb.append(letters.charAt(random.nextInt(letters.length())));
        }
        return sb.toString();
    }
}
